import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class TestJDBCInsert {
    public static void main(String[] args) throws SQLException {
        //1.创建数据源,数据源描述了你要操作的数据库在哪里
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/bite?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("111111");

        //2.和数据库服务器建立连接
        Connection connection = dataSource.getConnection();

        //3.构造SQL语句
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入id->: ");
        int id = scanner.nextInt();
        System.out.print("请输入姓名->: ");
        String name = scanner.next();
        String sql = "insert into people values (?,?)";
        //需要把String sql 转换成 语句对象
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);

        //4.把构造好的SQL发送给服务器去执行
        int n = statement.executeUpdate();
        System.out.println("n = " + n);

        //5.最后一步,释放必要的资源
        statement.close();
        connection.close();

    }
}
